var options, layer, table, form, upload, element;
var uploads_url = $("#uploads_url").val();
$(function () {
    //layui初始化，加载弹出层，表单等
    layui.use(['form', 'upload', 'table', 'excel', 'laypage', 'element'], function () {
        layer = layui.layer;
        form = layui.form;
        table = layui.table;
        upload = layui.upload;
        element = layui.element;

        // layer.config({
        //     skin: 'layui-layer-molv'
        // })

        element.on('tab(docDemoTabBrief)', function (elem) {
            var id = $(this).attr('lay-id');
            var url = $(this).attr('data-url');

            if (id !== '1') {
                $("#tpl_" + id).html('<iframe src="' + url + '" frameborder="0" style="width: 100%" ' +
                    'onload=\' this.style.height=Math.max(this.contentWindow.document.body.scrollHeight,this.contentWindow.document.documentElement.scrollHeight)+"px"; \'></iframe>');
                // notify.destroyAll();
            }

        });

        // input 监听回车事件
        $(".nav_search input").keydown(function (e) {
            // 当 keyCode 是13时,是回车操作
            if (e.keyCode == 13) {
                table.reload('form_table', {
                    where: form.val("search-form")
                    , page: {
                        curr: 1
                    }
                });
                $(".resetSearch").show();
                e.preventDefault();
                return false;
            }
        })


        form.on('submit(search)', function (data) {
            table.reload('form_table', {
                where: form.val("search-form")
                , page: {
                    curr: 1
                }
            });
            $(".resetSearch").show();
            return false;
        });

        form.on('submit(resetSearch)', function (data) {
            $(".search-form")[0].reset();
            table.reload('form_table', {
                where: form.val("search-form")
                , page: {
                    curr: 1
                }
            });
            $(".resetSearch").hide();
            return false;
        });

        //监听表格左侧工具栏
        table.on('tool(table)', function (obj) {
            try {
                tableTool(obj);
            } catch (e) {
                alert('发生错误了');
            }
        });
        //监听开关状态栏
        form.on('switch(status)', function (obj) {
            buttons.save(this.value, obj.elem.attributes[1].value, obj.elem.checked, $("#update_url").val());
        });
        form.on('switch(switch_old)', function (obj) {
            var val = $(this).prop('checked');
            var url = $(this).attr('url');
            $.get(url, {val: val})
        })
        form.on('switch(switch)', function (obj) {
            var val = $(this).prop('checked');
            var url = $(this).attr('url');
            $.get(url, {val: val})
        })
        //表单验证
        form.verify();

        $('.tableInput').change(function () {
            tableInput($(this));
        })

        form.on('select(tableInput)', function (obj) {
            tableInput($(obj.elem));
        });

        //添加配置页面，监听日期配置
        form.on('select(call_type)', function (obj) {
            if (obj.value == '7') {
                $("#time_format").css('display', 'block');
            } else {
                $("#time_format").css('display', 'none');
            }
        });

        //监听表单提交
        form.on('submit(save)', function (data) {
            layer.msg('<div><i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i> 加载中....', {
                shade: 0.8,
                time: 99999
            });
            var btn = $(this);
            btn.attr('disabled', true);
            formObj = $($(this).attr('formObj'));
            url = formObj.attr('action');
            $.ajax({
                type: 'POST',
                url: url,
                data: formObj.serialize(),
                dataType: "json",
                success: function (data) {
                    layer.closeAll();
                    if (data.code == 1) {
                        notify.success(data.msg, 1500, function () {
                            if (window.name != '') {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                                parent.window.location.reload();
                            } else {
                                window.location.reload();
                            }
                        });

                    } else {
                        notify.error(data.msg);
                        btn.removeAttr('disabled');
                    }
                },
                error(e) {
                    layer.closeAll();
                    btn.removeAttr('disabled');
                }
            });
            return false;
        })

        //单张图片上传
        upload.render({
            elem: '.uploadImage',
            url: uploads_url,
            before: function (obj) {
                layer.load();
                var showImage = this.item.find('.showImage');
                obj.preview(function (index, file, result) {
                    showImage.attr('src', result)
                });
            },
            done: function (data) {
                layer.closeAll();
                if (data.code == 200) {
                    this.item.find('.inpImage').val(data.data.url);
                    notify.success(data.msg);
                } else {
                    notify.error(data.msg);
                }
            },
            error: function () {
                layer.closeAll('loading');
            }
        });

        $('.showImages').on('click', '.uploadDels', function () {
            $(this).parent('.flex-li').remove();
        })

        $('.layui-table').on('click', '.openShowImg', function () {
            otherTool($(this), 'openShowImg');
        }).on('change', '.tableInput', function () {
            tableInput($(this));
        })

        $('.showVideo').on('click', '.uploadDels', function () {
            $(this).remove();
            $('.videoLink').attr('src', '');
            $('#video_link').val('');
            //video.load();
        })

        $('.showVideo2').on('click', '.uploadDels2', function () {
            $(this).remove();
            $('.videoLink2').attr('src', '');
            $('#content_videos').val('');
            //video.load();
        })

        upload.render({
            elem: '.uploadsBtn',
            url: uploads_url,
            multiple: true,
            before: function (obj) {
                var i = this.elem.index('.uploadsBtn');

                notify.loading('上传中...');
            },
            done: function (data) {
                notify.destroyAll();
                if (data.code == 200) {
                    var showImage = this.item.parent('.uploadsPrev').find('.showImages');
                    var inpName = this.item.parent('.uploadsPrev').find('.uploadsBtn').attr('inpName');
                    showImage.append('' +
                        '<li class="flex-li">' +
                        '<a target="_blank" href="' + data.data.url + '"><img class="flex-img" src="' + data.data.url + '"></a>' +
                        '<img class="uploadDels" src="http://dms.66km.com/static/img/marketing_delpic.png">\n' +
                        '<input type="hidden" name="' + inpName + '" value="' + data.data.url + '" class="uploadInps"/></li>')
                } else {
                    notify.error(data.msg);
                }
            },
            error: function () {
                notify.destroyAll();
                notify.error('上传失败');
            }
        });

        // //多张上传
        // upload.render({
        //     elem: '.uploadImages',
        //     url: uploads_url,
        //     multiple: true,
        //     before: function (obj) {
        //         layer.load();
        //         var i = this.elem.index('.uploadImages');
        //         obj.preview(function (index, file, result) {
        //             $('.showImages:eq(' + i + ')').append('' +
        //                 '<div class="imgContainer uploadImageBoxes">' +
        //                 '<img src="' + result + '" style="max-width: 100%">' +
        //                 '<br/>' +
        //                 '<a href="javascript:;" class="uploadDels">删除</a>' +
        //                 '</div>')
        //         });
        //     },
        //     done: function (data) {
        //         layer.closeAll();
        //         if (data.code == 200) {
        //             var i = this.elem.index('.uploadImages');
        //             var inpName = this.elem.attr('inpName');
        //             $('.showImages:eq(' + i + ')').append('<input type="hidden" name="' + inpName + '[]" value="' + data.data.url + '" class="uploadInps"/>');
        //             notify.success(data.msg);
        //         } else {
        //             notify.error(data.msg);
        //         }
        //     },
        //     error: function () {
        //         layer.closeAll('loading');
        //     }
        // });


        // $('.showImages').on('click', '.uploadDels', function () {
        //     var i = $(this).index('.uploadDels');
        //     $('.uploadImageBoxes:eq(' + i + ')').remove();
        //     // $('.uploadInps:eq(' + i + ')').remove();
        // })

    });

    /*富文本编辑器*/
    $('.editor').each(function () {
        UE.getEditor($(this).attr('id'), {scaleEnabled: true});
    })

    /*列表页checkbox开始*/
    tableCheck = {
        init: function () {
            layui.use('form', function () {
                layui.form.on('checkbox(list_all)', function (obj) {
                    var checked = obj.elem.checked;
                    $("[lay-filter=list_checkbox]").prop("checked", checked);
                    layui.form.render('checkbox');
                })
            })
        },
        getData: function () {
            var arr = [];
            $("[lay-filter=list_checkbox]:checked").each(function (i, e) {
                arr.push($(this).val());
            });
            return arr;
        }
    }
    tableCheck.init();
    var cateIds = [];

    function getCateId(cateId) {
        $("tbody tr[fid=" + cateId + "]").each(function (index, el) {
            id = $(el).attr('cate-id');
            cateIds.push(id);
            getCateId(id);
        });
    }

    $("tbody.x-cate tr[level!='0']").hide();

    //修改字段状态
    $('.x-show').click(function () {
        if ($(this).attr('status') == 'true') {
            $(this).html('&#xe625;');
            $(this).attr('status', 'false');
            cateId = $(this).parents('tr').attr('cate-id');
            $("tbody tr[fid=" + cateId + "]").show();
        } else {

            $(this).html('&#xe623;');
            $(this).attr('status', 'true');
            cateId = $(this).parents('tr').attr('cate-id');
            cateIds = [];
            getCateId(cateId);

            for (var i in cateIds) {
                $("tbody tr[cate-id=" + cateIds[i] + "]").hide().find('.x-show').html('&#xe623;').attr('status', 'true');
            }
        }
    })


    /** 公共菜单树单个展开与合并 */
    $('.show_menu').click(function () {
        let state = $(this).attr('data-state');
        let id = $(this).attr('data-id');
        if (state === 'hide') {
            $(".pid_" + id).css('display', '');
            $(this).attr('data-state', 'show');
            $(this).html('&#xe625;');
        } else {
            $(".pp" + id).css('display', 'none').find('.show_menu').attr('data-state', 'hide').html('&#xe623;');
            $(this).attr('data-state', 'hide');
            $(this).html('&#xe623;');
        }
    });

})


/** 菜单树全局展开与折叠 */
function openAllCate(that) {
    var text = $('.show_text').text();
    if (text == '展开') {
        $(".showAll").show();
        $('.show_text').text('折叠');
        $('.x-show').attr('status', 'false').html('&#xe625;');
    } else {
        $(".showAll").hide();
        $('.show_text').text('展开');
        $('.x-show').attr('status', 'true').html('&#xe623;');

    }

}

/** 公共获取表格内选中的数据 */
function getTable() {
    return table.checkStatus('form_table');
}


/** 公共弹出层 */
function zhiju_show(title, url, w, h, full = 0) {
    if (title == null || title == '') title = false;
    if (url == null || url == '') url = "404.html";
    if (w == null || w == '' || $(window).width() < w) w = ($(window).width() * 0.9);
    if (h == null || h == '' || $(window).height() < h) h = ($(window).height() - 50);
    if (full == '1') {
        let index = layer.open({
            type: 2,
            area: [w + 'px', h + 'px'],
            fix: false, //不固定
            maxmin: true,
            shadeClose: true,
            shade: 0.4,
            anim: 2,
            title: title,
            content: url,

        });
        layer.full(index);
    } else {
        layer.open({
            type: 2,
            area: [w + 'px', h + 'px'],
            fix: false, //不固定
            maxmin: true,
            shadeClose: true,
            shade: 0.4,
            anim: 2,
            title: title,
            content: url
        });
    }
}

/** 公共删除 */
function destroys(obj, url, id) {
    layer.confirm('确认要删除吗？', function (index) {
        layer.load(2);
        $.post(url, {id: id}, function (data) {
            layer.closeAll();
            if (data.code == 1) {
                $(obj).parents("tr").remove();
                notify.success(data.msg);
            } else {
                notify.error(data.msg);
            }
        });
    });
}

$(".search_open").click(function () {
    var text = $(this).text();
    if (text == '展开') {
        $(".hidden").removeClass('layui-hide');
        $(this).text('收起').addClass('search_close').removeClass('search_open');
    } else {
        $(".hidden").addClass('layui-hide');
        $(this).text('展开').addClass('search_open').removeClass('search_close');
    }
});